<template>
  <div>
    <van-nav-bar title="购物车" />
    <!-- 商品信息 -->
    <div v-for="(item, index) in list" class="shopgoods">
      <van-checkbox-group v-model="checked">
        <van-checkbox :name="item.id" @click="toggle(item.id, index)"></van-checkbox>
      </van-checkbox-group>
      <van-card :price="item.price" :title="item.name" :thumb="item.img">
        <template #footer>
          <van-button size="mini" :disabled="nums == 1 ? true : false" @click="subtract(index)">-</van-button>
          <span>{{ nums[index] }}</span>
          <van-button size="mini" @click="add(index)">+</van-button>
        </template>
      </van-card>
    </div>
    <!-- 结算 -->
    <van-submit-bar :price="goodsPrice" button-text="去结算" @submit="onSubmit">
      <van-checkbox v-model="checkedAll" @click="toggleAll">全选</van-checkbox>
    </van-submit-bar>
  </div>

</template>

<script setup>
import { ref } from 'vue'
import { useStore } from 'vuex';
const store = useStore()

// 单独点击商品，无法进行累计总和的计算值
//这个bug从点击事件入手


const checked = ref([])
const checkedAll = ref()

// 全选按钮实现
const toggleAll = () => {
  console.log(checked.value);
  console.log(checkedAll.value);
  if (checkedAll.value) {
    store.state.goodslist.forEach(item => {
      checked.value.push(item.id)
    });
    for (let i = 0; i < price.value.length; i++) {
      goodsPrice.value += price.value[i] * nums.value[i] * 100
    }
  } else {
    checked.value = []
    goodsPrice.value = 0
  }
}
// 单选控制全选
const goodsPrice = ref(0)
const toggle = (id, i) => {
  if (checked.value.length === store.state.goodslist.length) {
    checkedAll.value = true
  } else {
    checkedAll.value = null
  }
  // 商品总价计算
  if (checked.value.includes(id)) {
    console.log(checked.value);
    goodsPrice.value = price.value[i] * nums.value[i] * 100
    console.log(price.value[i]);
  } else {
    goodsPrice.value = (0)
  }
}

//商品单价汇总到一个数组
const price = ref([])
const priceAll = () => {
  store.state.goodslist.forEach(item => {
    price.value.push(item.price)
  });
  console.log(price.value);
}
priceAll()

// 商品数量
const nums = ref([])
//把商品数量存储
const numsAll = () => {
  store.state.goodslist.forEach(item => {
    nums.value.push(1)
  });
}
numsAll()

const subtract = (i) => {
  nums.value[i]--
}
const add = (i) => {
  nums.value[i]++
}

// 提交订单
const onSubmit = () => {

}

const list = ref()
list.value = store.state.goodslist
console.log(list.value);
</script>

<style lang="scss" scoped>
::v-deep .van-nav-bar {
  height: 50px;
  border-bottom: 1px solid #ccc;
}

::v-deep .van-submit-bar {
  margin-bottom: 50px;
}

.shopgoods {
  margin-bottom: 5px;
  display: flex;
  justify-content: space-around;
}

::v-deep .box {
  margin-top: 40px;
  width: 40px;
}

::v-deep .van-card {
  padding: 0;
}
</style>